Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

212
Views
creating function within function - method "buy" is not defined

I get the error method "buy is not defined.". What is wrong in the below code? Please can you let me know where I am going wrong?

var Portfolio = function() {

  let stockHoldings = new Map();
  
   function buy(trade) {
    let tradesForTicker = stockHoldings.get(trade.ticker);
    if(tradesForTicker == null){
      stockHoldings.set(trade.ticker,[trade]);
    }else{
      tradesForTicker.push(trade);
    }
  }

   function sell(trade) {
      let ticker = trade.ticker;  
      let tradesForTicker = stockHoldings.get(ticker);
      let precision = 5;
      if(tradesForTicker != null){
          let quantityToSell = Number(Number(trade.quantity).toFixed(precision));
          while(quantityToSell > 0) {
            quantityToSell = Number(Number(quantityToSell).toFixed(precision));          
            if(tradesForTicker.length > 0){
              let nextTradeToSell =  tradesForTicker[0];

              if(nextTradeToSell.quantity == quantityToSell){
                quantityToSell = 0;
                tradesForTicker.splice(0,1);
              } 
              else if (nextTradeToSell.quantity < quantityToSell){
                  quantityToSell = quantityToSell - nextTradeToSell.quantity;
                  tradesForTicker.splice(0,1);
              }else {
                nextTradeToSell.quantity = nextTradeToSell.quantity - quantityToSell;
                quantityToSell = 0;
              }
            }
          }
          if(tradesForTicker.length == 0){
            stockHoldings.delete(ticker)
          }
      }
  }

  this.stockHoldings = function() {
    return stockHoldings();
  }
};

function generetePortfolio(tickers, actions, quantities, prices){
  let portfolio = new Portfolio();
  for(var i=0;i< tickers.length; i++){
    let ticker = tickers[i].toString();
    let action = actions[i].toString();
    let quantity = quantities[i].toString();
    let price = prices[i].toString();

    let transactionTrade = new Trade(ticker,quantity,price,action);

    if(transactionTrade.isBuyOrDrip()){
        portfolio.buy(transactionTrade);
    }
    if(transactionTrade.isSell()){
      portfolio.sell(transactionTrade);
    }
  }
  return portfolio();
}

Further EDIT:

//Added method to generate total qty and avg price, BUT THIS DOES NOT WORK

function myPositions(tickers, actions, quantities, prices){
  let portfolio = generetePortfolio(tickers, actions, quantities, prices);  
  let returnArray = [];
  portfolio.stockHoldings.forEach((value, key) => {  
      let totalQuantity = 0;
      let avgPrice = 0;
      let totalCost = 0;
      value.map( trade => {
        totalQuantity += trade.quantity ;
        totalCost += trade.quantity * trade.price;
      });

      avgPrice = totalCost/totalQuantity;      
      returnArray.push([key, totalQuantity,avgPrice]);
  } )
  return returnArray;
}
about 4 years ago · Juan Pablo Isaza
1 answers
Answer question

0

You are trying to use properties of your portfolio object assuming that it will be an object based on Portfolio constructor but it is not.

A constructor function implicitly returns this. Now the only place you have used this inside the function is to attach one property stockHoldings to it.

You need to attach the other properties too.

What is happening under the hood can be thought of simply as : a local this empty object is created implicitly. It is returned in the end implicitly.

var Portfolio = function () {
 // this = {};  (implicitly)


  let stockHoldings = new Map();
  
   function buy(trade) {
    let tradesForTicker = stockHoldings.get(trade.ticker);
    if(tradesForTicker == null){
      stockHoldings.set(trade.ticker,[trade]);
    }else{
      tradesForTicker.push(trade);
    }
  }

   function sell(trade) {
      let ticker = trade.ticker;  
      let tradesForTicker = stockHoldings.get(ticker);
      let precision = 5;
      if(tradesForTicker != null){
          let quantityToSell = Number(Number(trade.quantity).toFixed(precision));
          while(quantityToSell > 0) {
            quantityToSell = Number(Number(quantityToSell).toFixed(precision));          
            if(tradesForTicker.length > 0){
              let nextTradeToSell =  tradesForTicker[0];

              if(nextTradeToSell.quantity == quantityToSell){
                quantityToSell = 0;
                tradesForTicker.splice(0,1);
              } 
              else if (nextTradeToSell.quantity < quantityToSell){
                  quantityToSell = quantityToSell - nextTradeToSell.quantity;
                  tradesForTicker.splice(0,1);
              }else {
                nextTradeToSell.quantity = nextTradeToSell.quantity - quantityToSell;
                quantityToSell = 0;
              }
            }
          }
          if(tradesForTicker.length == 0){
            stockHoldings.delete(ticker)
          }
      }
  }

  this.stockHoldings = stockHoldings;
  this.buy = buy;
this.sell = sell;

  // return this;  (implicitly)

};

function generetePortfolio(tickers, actions, quantities, prices){
  let portfolio = new Portfolio();
  for(var i=0;i< tickers.length; i++){
    let ticker = tickers[i].toString();
    let action = actions[i].toString();
    let quantity = quantities[i].toString();
    let price = prices[i].toString();

    let transactionTrade = new Trade(ticker,quantity,price,action);

    if(transactionTrade.isBuyOrDrip()){
        portfolio.buy(transactionTrade);
    }
    if(transactionTrade.isSell()){
      portfolio.sell(transactionTrade);
    }
  }
  return portfolio();
}

Also, the function for stockHoldings does not seem right. You should be returning the map right.

about 4 years ago · Juan Pablo Isaza Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!